package com.xingfly.service;

import io.jstack.sendcloud4j.SendCloud;
import io.jstack.sendcloud4j.mail.Email;
import io.jstack.sendcloud4j.mail.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 邮件服务
 * Created by SuperS on 2016/12/12.
 */
@Service
public class MailService {
    @Autowired
    private RedisTemplate<String, String> redis;
    public static final String ACCOUNT_KEY = "mail:account:";
    public static final String REST_KEY = "mail:rest:";
    private String mailApiKey = "rnAoc3agW0JQQUE3";
    private String mailApiUser = "XingFly";
    private String fromAddress = "admin@xingfly.com";
    private String fromName = "XingFly";
//    @Value("${mail.api.key}")
//    private String mailApiKey;
//    @Value("${mail.api.user}")
//    private String mailApiUser;
//    @Value("${mail.from.address}")
//    private String fromAddress;
//    @Value("${mail.from.name}")
//    private String fromName;

    private SendCloud webapi = SendCloud.createWebApi(mailApiUser, mailApiKey);

    /**
     * 发送邮件并
     *
     * @param from      发件地址
     * @param to        收件地址
     * @param mailTitle 邮件标题
     * @param htmlBody  邮件html内容
     * @param fromName  发件人名称
     * @return result 发送结果
     */
    private Result sendMail(String from, String to, String mailTitle, String htmlBody) {
        Email email = Email.general()
                .from(from)
                .fromName(fromName)
                .html(htmlBody)
                .subject(mailTitle)
                .to(to);
        return webapi.mail().send(email);
    }

    /**
     * 发送激活码到用户邮箱
     *
     * @param to  收信地址
     * @param key 激活key
     */
    public Result sendAccountActivationEmail(String to, String key) {
        String template = "<h1>你好,欢迎注册XingFly,激活码为:" + key + "。</h1>";
        return sendMail(fromAddress, to, "账户激活", template);
    }

    /**
     * 发送重置验证码到邮箱
     *
     * @param to  收信地址
     * @param key 激活key
     */
    public Result sendResetPwdEmail(String to, String key) {
        String template = "<h1>你好,重置验证码为:" + key + "</h1>";
        return sendMail(fromAddress, to, "重置密码", template);
    }

    /**
     * 添加ip到list
     *
     * @param ip ip地址
     */
    public void addIpToList(String key,String ip) {
        redis.opsForValue().set(key + ip, ip);
        redis.expire(key + ip, 60, TimeUnit.SECONDS);
    }

    /**
     * ip在列表中
     *
     * @param ip ip地址
     */
    public boolean isInList(String key,String ip) {
        if(redis.opsForValue().get(key + ip) == null){
            return false;
        }
        return true;
    }

}
